
/** 说明：转换设置运营参数后的模型为最终的页面数据定义模型（包含运营参数、约束条件等），
便于进行内容编辑、录入；
**/

var pageMetaParam = null;

function loadPageParams(){
	pageMetaParam = JSON.parse(fetchPageMetaParam());
	return transToPageModeMeta2(pageMetaParam,pageMeta);
}
 
function fetchPageMetaParam(){
	return null;
}


//transform page mode to actual page schema obj:
function transToPageModeMeta2(pageParam,rawMetaObj){ 
	var pageMeta2={};
	pageMeta2["type"] ="object"; 
	for(var k in rawMetaObj){
		if(k === "pageBlocks"){ 
			if(!pageMeta2["properties"]) pageMeta2["properties"] = {}; 
			pageMeta2["properties"]['pageBlocks'] = {};

			pageMeta2["properties"]['pageBlocks']['title'] = "页面区域定义";
			pageMeta2["properties"]['pageBlocks']['type'] = "object";

			pageMeta2["properties"]['pageBlocks']["properties"] =  
				buildPageBlocks2(pageParam[k],rawMetaObj[k]);

		}
/*
		else{
			if(k === "pageVars"){
				pageMeta2["properties"]["pageVars"] = buildArray2(pageParam[k],rawMetaObj[k]);
			}
			else{
				pageMeta2[k] = rawMetaObj[k];
			}
		}
*/
	}
	
	// console.log("page meta info:\n" + JSON.stringify(pageMeta2));
	return JSON.stringify(pageMeta2);
	//return false;
}


function buildPageBlocks2(blocksParam,rawPageBlocks){
	var ret = {};
	for(var b in rawPageBlocks){
		ret[b] = buildObject2(blocksParam[b],rawPageBlocks[b]);
	}
	return ret;
}


function buildObject2(paramDef,blockDef){
	var ret = {};
	for(var k in blockDef){
		if(k === "properties" ){
			var to = blockDef[k];
			if(to ){
				ret[k] = {};
				for(var pk in to){	 //for each prop
					var prop = to[pk];
					if(prop["type"]){
						var t = prop["type"];
						if(t === "object"){
							ret[k][pk] = buildObject2(paramDef[pk],prop);
						}
						else if(pagemeta.extTypes.hasOwnProperty(t)){	//是自定义类型？
								var bp = transStandartType(t,paramDef[pk],prop);
								
								ret[k][pk] = bp;
							}
							else{	//json内置类型
								throw "未知类型:" + t +"，请检查页面结构定义文件\n节点信息：\n" + JSON.stringify(to);
								var bp = {};
								for(var tpk in prop){
									bp[tpk] = prop[tpk];
								}
								ret[k][pk] = bp;									
							}
					}
				}
			}
			else
				ret[k] = b[k];
		}
		else{
			ret[k] = blockDef[k];
		}
	}
	return ret;
}

/*
function buildObject2(paramDef,blockDef){ 
	var ret = {}; 
	for(var k in blockDef){
		var to = blockDef[k];
		if(k === "properties" ){
			if(to){
				ret[k] = {};
				for(var pk in to){	 //for each prop
					var prop = to[pk];
					if(prop["type"]){
						var t = prop["type"];
						if(t === "object"){
							ret[k][pk] = buildObject2(paramDef[pk],prop);
						}
						else
							if(t === "array"){
								ret[k][pk] = buildArray2(paramDef[pk],prop);
							}
							else if(t === "TArrayDef"){								
								var tobj = buildArray2(paramDef[pk],prop);
								tobj["type"] = "array";
								ret[k][pk] = tobj;
								//ret[k][pk] = buildBuildInArrayType(prop);	
							}
							else{
								//prop is buildin type:to transform to standart json schema type
								var bp = transStandartType(paramDef[pk],prop);
								ret[k][pk] = bp;
							}
					}
				}
			}
			else
				ret[k] = b[k];
		}
		else{
			ret[k] = to;
		}
	}
	if(blockDef["title"]) ret["title"] = blockDef["title"];
	ret["type"] = "object";

	return ret;
}
function buildArray2(paramDef,prop){
	var ret = {};
	for(var i in prop){
		if(i === "items"){
			ret[i] = buildObject2(paramDef,prop[i]);
		}
		else if(i === 'properties'){	//treate TArrayDef ...		
			ret['items'] = buildObject2(paramDef,prop[i]['items']);
			buildArrayObj(ret,paramDef,prop[i]);
		}
		else{
			ret[i] = prop[i];
		} 
	} 
	ret['type'] = "array";
	return ret;
}


function buildArray2(paramDef,prop){
	var ret = {};
	for(var i in prop){
		if(i === "items"){
			ret[i] = buildObject2(paramDef[i],prop[i]);
		}
		else{
			ret[i] = prop[i];
		}
	} 
	if(paramDef.maxItems) ret['maxItems'] = paramDef.maxItems;
	if(paramDef.minItems) ret['minItems'] = paramDef.minItems;
	
	ret['type'] = "array";
	return ret;
}
*/

function transStandartType(type,paramDef,propDef){
	var clz = pagemeta.initComponent(type);
	var ret = {}; 
	//滤除数据定义部分
	var props = clz.jsonObj['properties'];
	//是原始类型封装？
	if(props['__wrappedType']){
		for(var p in props['__wrappedType']){
			if(p === '__validationRule'){	// 存在json校验条件定义
				for(var vp in props['__wrappedType'][p]){
					ret[vp] = paramDef[vp];
				}
			}	
			else{
				ret[p] = props['__wrappedType'][p];
			}
		}
	}
	else{	//是自定义类型，递归处理；
		if(type === "TArrayDef"){
			for(var p in propDef){
				if(p === "items")
					if(propDef[p]['type'] === 'object')
						ret[p] = buildObject2(paramDef[p],propDef[p]);
					else{
						var tp = propDef[p]['type'];
						if(tp && pagemeta.extTypes.hasOwnProperty(tp)){	//是内置类型，需要递归装载定义
							ret[p]= transStandartType(tp,paramDef[p],propDef[p]);	
						}
						else{
							//会出现这种情况吗？
						}
					}
				else
					ret[p] = propDef[p];
			}
			if(paramDef.maxItems) ret['maxItems'] = paramDef.maxItems;
			if(paramDef.minItems) ret['minItems'] = paramDef.minItems;
		}
		else //self-def type wrapped 
			for(var p in clz.jsonObj){ 
				if(p === "properties"){
					ret[p]={};
					for(var sp in clz.jsonObj[p]){
						var tp = clz.jsonObj[p][sp]['type'];
						if(tp && pagemeta.extTypes.hasOwnProperty(tp)){	//是内置类型，需要递归装载定义
							ret[p][sp] = transStandartType(tp,paramDef[sp],clz.jsonObj[p][sp]);	
						}
						else{
							//会出现这种情况吗？
						}
					}

				}
				else
					ret[p] = clz.jsonObj[p];
		}	
	} 

	//修正类型为json内置类型
	ret['type'] = ajustType(type);
	if(propDef['format'] && propDef) ret['format'] = propDef['format'];
	if(propDef['title'] && propDef) ret['title'] = propDef['title'];	//copy title def
	if(propDef['options']){
		ret['options'] =deepCopy({},propDef['options']); 
	}

	return ret;
} 

function ajustType(type){
	if(type === "TTextDef" || type === "TLinkDef" || type ===  "TPictureDef" || type === "TRichTextDef"){
		return "string";
	}
	else if(type === "TArrayDef"){
		return "array";
	}
	else if(type === "TIntegerDef")
		return "integer";
	else if(type === "TBooleanDef")
		return "boolean";
	else if(type === "TNumberDef")
		return "number";
	else
		return "object";
}


    /**
    **  jsoneditor 对象初始化完毕后的处理函数，用于进行进一步的规范处理；
    **  需要同步将页面模型扩展信息同时加载进来，该json对象为：extMetaJson
    **   同时编辑用户的所属等级变量已经确定，变量名为：editorLevel;
    **/
    var extMetaJson = null;
    var editorLevel = "1";
    var extCntJson = {};	//内存中的内容扩展信息JSON对象，用于动态记录用户的扩展信息修改；
    function postCntReadyFunc(){
    	//only for demo
    	if(document.getElementById("ext_schema").value)
    		extMetaJson =JSON.parse( document.getElementById("ext_schema").value);
    	else
    		extMetaJson = "{}";
    	var slt = document.getElementById("sltEditorLevel");
    	if(slt.selectedIndex != 0){
    		editorLevel = slt.options[slt.selectedIndex].value;
    	}

        console.log("json editor is ready!" );
        var editors = jsoneditor_cnt.editors;
        if(editors){
        	for(var ei in editors){
        		var e = editors[ei];
        	//resize sceditor
        	if(e.sceditor_instance){
        		e.sceditor_instance.width("100%");
        		e.sceditor_instance.height("300");        
        	}
        		
	        //检查广告对象：增加options选型isAd，表明该数据元素是否为广告
	        if(e.options && e.options.isAd === true){
				///////////////////广告处理函数段////////////////////////////////

				//检查：广告排期处理
			console.log("Ad scheduling : " + e.path);
			//TODO：需要检查数组元素最大数量和最小数量是否相同，不同提示用户并不做后续处理；

			//get obj's title area
			var tTitle = null;
			if(e.schema.type ===  "array" || e.schema.type === "object")
				tTitle  = getObjDefTitleArea(e.jsoneditor,e.path);
			else
				tTitle =  getObjPropDefTittleArea(e.jsoneditor,e.path);

			if(tTitle){
				var funcBut = getFuncButton(e.jsoneditor,"广告排期设置",function(){
					//demo:only demo:)
					window.open('widget/ext/ADsetting_demo.html?path=xxx');
				});
				tTitle.appendChild(funcBut);
			}
	        }
	        //检查是否为数组：基于位置的授权
	        if(e.options && e.options.assignByIndex === true){
	        	if(!extMetaJson || !extMetaJson.assignByIndex || !extMetaJson.assignByIndex[e.path])
	        		continue; 
	        	var setting = extMetaJson.assignByIndex[e.path];
	        	//like: {"assignByIndex":{"root.pageBlocks.A4GAd.adRoll":{"0":"1","1":"2","2":"3","3":"1"}}}
	        	if(setting){
	        		var arrayExt = {};
	        		if(!extCntJson.assignByIndex)
	        			extCntJson.assignByIndex ={};
	        		extCntJson.assignByIndex[e.path] = arrayExt;	 
	        		/**首先disalbe所有数组内容：禁止增加、删除、修改顺序
	                   	 对于位置有权限的位置，设置该node ：
	                        //调用enable()，开放修改;（增加、删除、修改仍然不能操作）
	                        在该节点的标题位置，增加checkbox，标题为：启动该位置，默认为不勾选，系统为disable
	                        如果用户勾选该选项，则调用enable()方法，启用该节点。同时在输出的扩展数据中，增加该启用位置标识的信息，便于后续数据使用时参考；
			*/
			e.disable();
			for(var il in setting){
				var ll = setting[il];
				//editor's row
				var row = e.tabs_holder.childNodes[0].childNodes[il];
				var edt = jsoneditor_cnt.getEditor(e.path+"."+il);
				if(!row || !edt) continue;
				arrayExt[il] = {"level":ll};
				var chk = appendCheckBox(row,il,edt,arrayExt);
				if(!chk) continue;
				if(ll === editorLevel){
					chk.checked = true;
					edt.enable();
					arrayExt[il]["used"]=true; 
				}
				else{
					chk.checked = false;
					chk.disabled = true;
					edt.disable();
					arrayExt[il]["used"]=false; 
				}
			}

	        	}	
	        }
	        //检查是否为多级编辑内容："multiLevelEdite":true     //默认为false
	         
				if(e.options && e.options.multiLevelEdite){
					multiLevelEditeBy2(e);
				}
        	}
        }
    }


	///////////////////多级编辑处理函数段////////////////////////////////

	//检查是否为多级编辑内容："multiLevelEdite":true     //默认为false
	function multiLevelEditeBy2(node){  
		//get obj's title area
		var tTitle = getObjPropDefTittleArea(node.jsoneditor,node.path);
		if(tTitle){
			var funcBut = getFuncButton(node.jsoneditor,"编辑发布内容",function(){
// 				alert("TODO：处理的外部逻辑，设置完毕数据回传");
				//demo:only demo:)
				window.open('widget/ext/multiLevelEdite_edit.html?path=xxx&arraySize=4');
			});
			tTitle.appendChild(funcBut);
		}
	}

	/**
	**	在弹出窗口内设置完数组后，将最终数据回传给jsoneditor组件处理
	**/
	function multiLevelEditeCallback2(path,settings){
// 		console.log(settings);
// 		alert(path + ":" + settings);
		//在这里接收数据并填充到处理扩展数据中；
		if(!extCntJson.multiLevelEdite) extCntJson.multiLevelEdite={}; 
		extCntJson.multiLevelEdite[path] = settings;
		var output_schema = document.getElementById("ext_cnt");
		if(output_schema){
// 			var jsn = output_schema.value;
// 			if(!jsn) jsn="{}";
// 			var jsnObj = JSON.parse(jsn);
// 			if(!jsnObj.multiLevelEdite) jsnObj.multiLevelEdite = {};
// 			jsnObj.multiLevelEdite[path] = settings;
			output_schema.value = JSON.stringify(extCntJson);
		}
		//在这里接收数据并填充到处理扩展数据中；
	}




    function appendCheckBox(row,idx,edt,arrayExt){
    	var span = row.childNodes[0];
    	if(span){
    	 	var chk = getFormInputField('checkbox');    	 	
		chk.style.display = 'inline-block';
		chk.style.width = 'auto';
		chk.addEventListener("click",function(e){
        		e.stopPropagation();
// 			console.debug("check box:"+e);
			if(chk.checked){
				edt.enable();
				arrayExt[idx]["used"] = true;
			}
			else{
				edt.disable();
				arrayExt[idx]["used"] = false;
			}

		});
		var sp = document.createElement("span");
		sp.innerText = " ";
		span.appendChild(sp)
		chk.alt="是否启用标志";
		span.appendChild(chk);
		return chk;
    	}
    	return null;
    }

 function genExtCnt(){
 	var extCtl = document.getElementById("ext_cnt");
	if(extCtl && extCntJson){
		//change track

		if(cntChangeList){
			extCntJson['cntChangeList'] = cntChangeList;	
		}
		extCtl.value = JSON.stringify(extCntJson);
	} 	
 }


 /**
 ** 图片上传处理函数
 **/
      // Specify upload handler
      
//       JSONEditor.defaults.options.theme = 'html';
      JSONEditor.defaults.options.upload = function(type, file, cbs,editor) {
        if (type === 'root.upload_fail') cbs.failure('Upload failed');
        else {
		//在这里检查文件参数信息：
		if(editor.schema.fileType){
			//"*.jpg,*.gif,*.png"
// 			cbs.failure("只能选择："+editor.schema.fileType);
// 			alert("只能选择："+editor.schema.fileType);
// 			return;
		}
		//最大最小值
		if(editor.schema.maxSize){
			//TODO:
		}
		if(editor.schema.minSize){
			//TODO
		}
          var tick = 0;

          var tickFunction = function() {
            tick += 1;
            console.log('progress: ' + tick);

            if (tick < 100) {
              cbs.updateProgress(tick);
              window.setTimeout(tickFunction, 50)
            } else if (tick == 100) {
              cbs.updateProgress();
              window.setTimeout(tickFunction, 500)
            } else {
              cbs.success('http://www.example.com/images/' + file.name);
            }
          };

          window.setTimeout(tickFunction)
        }
      };



/**
** 跟踪用户修改信息
**/
var cntChangeList = {};
function eventChanged(ctrl,actionType){
	if(ctrl && ctrl.path && ctrl.jsoneditor === jsoneditor_cnt){	//is page content editor
		console.log("Event change:" + ctrl.path + ", actionType:"+actionType);
		if(!cntChangeList[ctrl.path]) cntChangeList[ctrl.path] = [];
		cntChangeList[ctrl.path].push(actionType);
	}
	else{
// 		console.log("change invalided event:" + ctrl);
	}
	//show changed element's label bg-color to red:
	//getObjPropDefTittleArea(jsoneditor_cnt,"root.pageBlocks.A4GAd.adRoll.2.url").style['background-color']="#FF0000"
}


//重新装载内容扩展信息函数：
function restoreCntExt(editor,extJsonStr){
	var extJson = JSON.parse(extJsonStr);
	//处理修改对象将标题变红：
	if(extJson){
		if(extJson.cntChangeList){
			var chgs = extJson.cntChangeList;
			for(var i in chgs){
				var node = editor.getEditor(i);
				if(node.schema.type!='object' && node.schema.type!="array"){
					getObjPropDefTittleArea(editor,i).style['background-color']="#FF0000";
				}
				else{
					getObjDefTitleArea(editor,i).style['background-color']="#FF0000";
				}
			}
		}
	}
}

/*
{ 
	var bp = {};  
	for(var tpk in prop){	
		bp[tpk] = prop[tpk];
	}
	if(type === 'TTextDef'){
		buildTextObj(bp,paramDef,prop);
	}
	else if(type === 'TPictureDef'){		
		bp['format'] = 'url';
		bp['type'] = 'string';
	}
	else if(type === 'TLinkDef'){
		bp['format'] = 'url';
		bp['type'] = 'string';
	}
	else if(type === "TTextLinkDef"){
    	bp["type"]="object";
    	bp["properties"] = {};
    	var txtObj = {};
    	buildTextObj(txtObj,paramDef['linkTitle'],prop);
    	bp['properties']['linkTitle'] = txtObj;  
    	bp['properties']['url'] = {    		
            "title":"链接地址",
            'type':"string"
    	};
    	if(paramDef['url'] && paramDef['url']['url'] )
    		bp['properties']['url']['default'] = paramDef['url']['url'];
    }  
	else if(type === 'TPicLinkDef'){
    	bp["type"]="object";
    	bp["properties"] = { 		
            "picture":{
                "title":"链接图片"
            },
            "url":{
                "title":"链接地址"
            }
    	};

	}
	else if(type === "TArrayDef"){
		bp = buildArray2(paramDef,prop);
	}
	else{
		throw "unkown type:" + tyep;

	}

	return bp;
}

function buildTextObj(bp,paramDef,prop){
	bp['type'] = 'string';
	for(var k in paramDef){
		if(k === 'texttype'){
			//TODO:set format ....
		}
		if(k === 'default') bp[k] = paramDef[k];
		if(k === 'maxLength') {
			if(paramDef[k][k]) bp[k] = paramDef[k][k];
			if(paramDef[k]['includeEdge']) {
				//TODO: set upper edge
			}
		}
		if(k == 'minLength'){			
			if(paramDef[k][k]) bp[k] = paramDef[k][k];
			if(paramDef[k]['includeEdge']) {
				//TODO: set down edge
			}
		}
	}
}

*/